package sms

import (
	"context"
	"encoding/json"
	"fmt"
	"gitcode.com/G-YT/baoyou/server/global"
	"gitcode.com/G-YT/baoyou/server/utils/request"
	"io"
	"time"
)

// SMSResponse 短信发送响应结构
type SMSResponse struct {
	Status string `json:"status"`
	SendID string `json:"send_id,omitempty"`
	Fee    int    `json:"fee,omitempty"`
	Code   string `json:"code,omitempty"`
	Msg    string `json:"msg,omitempty"`
}

func SendSMS(mobile string, code string) error {
	appid := global.GVA_CONFIG.Submail.AppID
	appkey := global.GVA_CONFIG.Submail.AppKey
	project := global.GVA_CONFIG.Submail.Project
	url := global.GVA_CONFIG.Submail.URL

	headers := map[string]string{
		"content-type": "application/json",
	}
	params := map[string]string{}
	data := make(map[string]any)

	data["appid"] = appid
	data["signature"] = appkey
	data["to"] = mobile
	data["project"] = project
	data["vars"] = map[string]string{
		"code": code,
	}

	res, err := request.HttpRequest(url, "POST", headers, params, data)
	if err != nil {
		return fmt.Errorf("发送短信请求失败: %w", err)
	}
	defer res.Body.Close()

	// 读取响应体
	body, err := io.ReadAll(res.Body)
	if err != nil {
		return fmt.Errorf("读取响应体失败: %w", err)
	}

	// 解析响应JSON
	var smsResp SMSResponse
	if err := json.Unmarshal(body, &smsResp); err != nil {
		return fmt.Errorf("解析响应JSON失败: %w, 响应内容: %s", err, string(body))
	}

	// 检查响应状态
	if smsResp.Status != "success" {
		return fmt.Errorf("短信发送失败: code=%s, msg=%s", smsResp.Code, smsResp.Msg)
	}

	// 发送成功，将验证码存入Redis
	ctx := context.Background()
	redisKey := fmt.Sprintf("phone::%s::code", mobile)
	if err := global.GVA_REDIS.Set(ctx, redisKey, code, 5*time.Minute).Err(); err != nil {
		return fmt.Errorf("验证码存入Redis失败: %w", err)
	}

	return nil
}

func CheckSMSCode(mobile string, code string) error {
	ctx := context.Background()
	redisKey := fmt.Sprintf("phone::%s::code", mobile)
	storedCode, err := global.GVA_REDIS.Get(ctx, redisKey).Result()
	if err != nil {
		return fmt.Errorf("获取验证码失败: %w", err)
	}

	if storedCode != code {
		return fmt.Errorf("验证码不匹配")
	}

	return nil
}
